<?php

namespace app\api\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Cache;

class SyncStock extends Command
{
    protected function configure()
    {
        $this->setName('sync:stock')->setDescription('同步股票数据');
    }

    protected function execute(Input $input, Output $output)
    {
        $data = $this->updateStockByRedis();
     
        if( !$data )
            return;
        
        // 截断数据表
        Db::execute("truncate table `sx_stock`");

        $newData = [];
        $mapStockCodeList = [];
        $redis = Cache::store('redis')->handler();
        foreach ($data as $item) {
            // 获取需要匹配的字段值
            $code = $item['dm'];
            $name = $item['mc'];
            $allNo = $item['jys'] . $code;
            
            $newData[] = [
                'no'    => $code,
                'all_no' => $allNo,
                'name'   => $name,
            ];
            $mapStockCodeList[$allNo] = $code;
        }
        Db::name('stock')->insertAll($newData);
        
        $stockListKey = 'stock:hash:pricelist';
        if( empty( $mapStockCodeList) == false ){
            $redis->hmset($stockListKey, $mapStockCodeList);
        }
        $output->writeln('股票数据处理成功！');
        
    }

    /**
     * 获取最新最新股票列表
     */
    protected function updateStockByRedis()
    {
        // 获取API许可证
        $licence = "0025291A-8409-8A3D-8670-812F005C5E3B";
        // API请求地址
        $url = "https://ig507.com/data/base/gplist?licence=" . $licence;

        $response = $this->https_request($url);

        return json_decode($response, true);
    }

    /**
     * http请求方法
     */
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
